package org.itboys.seller.service;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.seller.constant.CaliforniaSiteConstant;
import org.itboys.seller.dto.SiteUserVO;
import org.itboys.seller.entity.SiteUser;
import org.itboys.seller.entity.SiteUserEdit;
import org.itboys.seller.meta.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商家登陆账号
 * @author weisky
 *
 */
@Service
public class SiteUserEditService extends BaseService<SiteUserEdit, Long>{
	
	private static final long serialVersionUID = 1L;

	@Resource(name = "sellerDS")
	private MongoDataSource ds;

	@Autowired
	private AccountService accountService;

	@Autowired
	private CaliforniaSiteUserService californiaSiteUserService;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<SiteUserEdit> getEntityClass() {
		return SiteUserEdit.class;
	}

	/**
	 * 修改或保存
	 * @param sellerUser
	 * @return 0:系统错误  1：成功  2：用户名已存在
	 */
	public int insert(SiteUserEdit siteUserEdit){
		try{

			if(siteUserEdit.getId() != 0){//修改
				SiteUserEdit sellerUser2 = getById(siteUserEdit.getId());
				if(StringUtils.isEmpty(siteUserEdit.getPassword())){//密码为空
					siteUserEdit.setPassword(sellerUser2.getPassword());//若是密码为空  就设置成原来的密码
				}
				update(siteUserEdit);
			}else{//新增
				siteUserEdit.setState(CaliforniaSiteConstant.TYPE_ONE);
				save(siteUserEdit);
//                addPersons(sellerUser);
			}
			return 1;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.insert error", e);
			return 0;//失败
		}
	}

	/**
	 * 根据用户名查询用户
	 *
	 * @return
	 */
	public SiteUserEdit getAdminUserByUserId(long userId) {
		// 用户名转小写再查
		List<SiteUserEdit> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("userId", userId).asList();
		return list==null||list.isEmpty()?null:list.get(0);
	}

	/**
	 * 分页查询
	 *
	 * @param id
	 * @return
	 */
	public Page<SiteUserVO> pageQueryAll(HttpServletRequest request) {
		Page<SiteUserEdit> page = pageQuery(request);
		List<SiteUserEdit> siteUserList = page.getData();
		List<Long> userIds = siteUserList.stream().map(SiteUserEdit::getUserId).collect(Collectors.toList());
		List<Long> recUserIds = siteUserList.stream().map(SiteUserEdit::getRecUserId).distinct().collect(Collectors.toList());
        recUserIds.addAll(siteUserList.stream().map(SiteUserEdit::getRecUserId2).distinct().collect(Collectors.toList()));
		List<SiteUser> recSiteUsers = californiaSiteUserService.getAdminUserByUserIds(recUserIds);
		Map<Long, SiteUser> recSiteUserMap = recSiteUsers.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
		List<Account> accounts = accountService.batchQueryAccount(userIds);
		Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
		List<SiteUserVO> voList = siteUserList.stream().map(p -> {
			SiteUserVO vo = new SiteUserVO();
			vo.setId(p.getId());
			vo.setUserId(p.getUserId());
			vo.setMemberName(p.getMemberName());
			vo.setCompanyName(p.getCompanyName());
			vo.setPhone(p.getPhone());
			vo.setRecUserId(p.getRecUserId());
			vo.setRealName(p.getRealName());
			vo.setIdCard(p.getIdCard());
			Account account = accountMap.get(p.getUserId());
			if (account != null) {
				vo.setAmount(account.getAmount());
			}
			SiteUser recSiteUser = recSiteUserMap.get(p.getRecUserId());
			if (recSiteUser != null) {
				vo.setRecMemberName(recSiteUser.getRealName());
			}
            recSiteUser = recSiteUserMap.get(p.getRecUserId2());
            if (recSiteUser != null) {
                vo.setRecMemberName2(recSiteUser.getRealName());
            }
			vo.setAuditState(p.getAuditState());
			vo.setAuditName(p.getAuditName());
			vo.setUpdateTime(p.getUt());
            vo.setMemberType(p.getMemberType());
            vo.setArea(p.getArea());
			return vo;
		}).collect(Collectors.toList());
		return new Page<SiteUserVO>(voList, page.getPageNo(), page.getPageSize(), page.getTotal());
	}
}
